﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Web;
using System.Data;

namespace AAA.Web
{
    public class ExportHelper
    {
        public static void GridViewToCSV(GridView gvSource, string strFilename)
        {
            try
            {
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Buffer = true;
                HttpContext.Current.Response.AddHeader("Content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(strFilename, System.Text.Encoding.UTF8));
                HttpContext.Current.Response.Charset = "big-5";
                HttpContext.Current.Response.ContentType = "application/text";

                StringBuilder sb = new StringBuilder();
                for (int k = 0; k < gvSource.Columns.Count; k++)
                {
                    //add separator
                    sb.Append(gvSource.Columns[k].HeaderText + ',');
                }
                //append new line
                sb.Append(Environment.NewLine);
                for (int i = 0; i < gvSource.Rows.Count; i++)
                {
                    for (int k = 0; k < gvSource.Columns.Count; k++)
                    {
                        //add separator
                        sb.Append(gvSource.Rows[i].Cells[k].Text + ',');
                    }
                    //append new line
                    sb.Append(Environment.NewLine);
                }
                HttpContext.Current.Response.Output.Write(sb.ToString());
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.End();
            }
            catch (Exception ex)
            {
            }
        }

        public static void GridViewToExcel(GridView gvSource, string strFilename)
        {
            try
            {
                HttpContext.Current.Response.ClearContent();
                HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>");
                HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(strFilename, System.Text.Encoding.UTF8));
                HttpContext.Current.Response.ContentType = "application/ms-excel"; 
                System.IO.StringWriter stringWrite = new System.IO.StringWriter(); 
                System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); 
                gvSource.RenderControl(htmlWrite);
                HttpContext.Current.Response.Write(stringWrite.ToString());
                HttpContext.Current.Response.End(); 
            }
            catch(Exception ex)
            {
            }
        }

        public static void ExportDataTableToExcel(DataTable dtSource, string strFilename)
        {            
            int tRowCount = dtSource.Rows.Count;
            int tColumnCount = dtSource.Columns.Count;

            HttpContext.Current.Response.Expires = 0;
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.Charset = "utf-8";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            //設定檔名可為中文_#1
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"" + HttpUtility.UrlEncode(strFilename, System.Text.Encoding.UTF8) + "\"");

            //引用這三個xmlns
            HttpContext.Current.Response.Write("<html xmlns:o='urn:schemas-microsoft-com:office:office'");
            HttpContext.Current.Response.Write("xmlns:x='urn:schemas-microsoft-com:office:excel'");
            HttpContext.Current.Response.Write("xmlns='http://www.w3.org/TR/REC-html40'>");

            HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>");

            //在head中加入xml定義
            HttpContext.Current.Response.Write("\n <head>");
            HttpContext.Current.Response.Write("\n <xml>");
            HttpContext.Current.Response.Write("\n <x:ExcelWorkbook>");
            HttpContext.Current.Response.Write("\n <x:ExcelWorksheets>");
            HttpContext.Current.Response.Write("\n <x:ExcelWorksheet>");
            //設定此Worksheet名稱_#2
            HttpContext.Current.Response.Write("\n <x:Name>" + strFilename.Replace(".xls", "") + "</x:Name>");

            //以下針對此工作表進行屬性設定
            HttpContext.Current.Response.Write("\n <x:WorksheetOptions>");
            HttpContext.Current.Response.Write("\n <x:FrozenNoSplit/>");

            //設定凍結行號_#3
            HttpContext.Current.Response.Write("\n <x:SplitHorizontal>1</x:SplitHorizontal>");

            //設定起始行號(TopRowBottomPane)_#4
            HttpContext.Current.Response.Write("\n <x:TopRowBottomPane>2</x:TopRowBottomPane>");
            HttpContext.Current.Response.Write("\n <x:ActivePane>2</x:ActivePane>");
            HttpContext.Current.Response.Write("\n </x:WorksheetOptions>");
            HttpContext.Current.Response.Write("\n </xml>");
            HttpContext.Current.Response.Write("\n </head>");

            HttpContext.Current.Response.Write("\n <body>");
            HttpContext.Current.Response.Write("<Table borderColor=black border=1>");
            HttpContext.Current.Response.Write("\n <TR>");

            //塞入head
            for (int i = 0; i < tColumnCount; i++)
            {
                //設定head的背景色_#5
                HttpContext.Current.Response.Write("\n <TD  bgcolor = #fff8dc>");
                HttpContext.Current.Response.Write(dtSource.Columns[i].ColumnName);
                HttpContext.Current.Response.Write("\n </TD>");
            }

            HttpContext.Current.Response.Write("\n </TR>");

            //塞入每一筆資料
            for (int j = 0; j < tRowCount; j++)
            {
                HttpContext.Current.Response.Write("\n <TR>");
                for (int k = 0; k < tColumnCount; k++)
                {
                    if (j % 2 == 0)
                    {
                        //設定單號資料靠左且背景為綠色_#6
                        HttpContext.Current.Response.Write("\n <TD align=\"left\" x:num bgcolor = ADFF2F>");
                        HttpContext.Current.Response.Write(dtSource.Rows[j][k].ToString());
                        HttpContext.Current.Response.Write("\n </TD>");
                    }
                    else
                    {
                        //設定雙號資料靠右_#7
                        HttpContext.Current.Response.Write("\n <TD align=\"right\" x:num>");
                        HttpContext.Current.Response.Write(dtSource.Rows[j][k].ToString());
                        HttpContext.Current.Response.Write("\n </TD>");
                    }
                }
                HttpContext.Current.Response.Write("\n </TR>");
            }

            HttpContext.Current.Response.Write("</Table>");
            HttpContext.Current.Response.Write("</body>");
            HttpContext.Current.Response.Write("</html>");
            HttpContext.Current.Response.End();
        }

    }
}
